import React from 'react'
import $ from 'jquery'
import {
    R_header_fixed
} from '../common/index'
import '../../plugins/city/js/LArea.js'
import {
    HttpService,
    dateFormat,
    browser,
    GetDateStr,
    ApiUploadImg,
    fmtDate,
    sxtUploadImgUse,
    haveEmoji
} from '../../Tools'
import {
    Toast
} from '../../Http'
import DatePicker from 'react-mobile-datepicker'
import {
    Checkbox,
    InputNumber
} from 'antd'
import './style/business.scss'
import Chose from './img/chose.png'
import {
    Cascader
} from 'antd'
export default class AddGoods extends React.Component {
    constructor(props) {
        super(props)
        this.title = "添加商品"
        this.areaId = "";
        this.address = [];
        this.goodId = this.props.params.goodId;
        this.goodDatas;
        this.state = {
            contentNumber: 0,
            isOpen: false,
            value: new Date(GetDateStr(0)),
            min: new Date(GetDateStr(0)),
            max: undefined,
            options: [],
            areaId: ''
        }
    }

    static contextTypes = {
        router: React.PropTypes.object.isRequired
    };

    componentWillMount() {
        var rec = this;
        $.ajax({
            url: '/region/getRegions',
            type: "post",
            async: false,
            data: {
                uuid: 'china'
            },
            success: function(res) {
                if (res.code == 50006) {
                    var allData = [];
                    for (var i = 0; i < res.data.length; i++) {
                        allData.push({
                            value: res.data[i].uuid,
                            label: res.data[i].orgName,
                            isLeaf: false
                        })
                    }

                    rec.setState({
                        options: allData
                    })
                } else {
                    Toast.toast(res.data)
                }
            },
            error: function(res) {
                Toast.toast(res.data)
            }
        })

        //商品修改赋值
        const goodId = this.goodId;
        if (goodId) {
            this.title = '修改商品'
            $.ajax({
                url: '/jf/business/goodsArchives/getJfGoodsArch',
                type: "post",
                data: {
                    token: localStorage.btoken,
                    goodsArchId: goodId
                },
                success: function(res) {
                    let refs = rec.refs;
                    let result = res.data;

                    //保存数据和提交的时对比是否改变
                    rec.goodDatas = result;

                    let type = '';
                    //商品图
                    var headpicS = document.getElementById('headpicS')
                    var detailpicS = document.getElementById('detailpicS')
                    var couponpicS = document.getElementById('couponpicS')

                    headpicS.src = JSON.parse(result.smallImg).goodsHeaderImg;
                    detailpicS.src = JSON.parse(result.smallImg).goodsDetailsImg;

                    if (JSON.parse(result.smallImg).couponImg != "") {
                        couponpicS.src = JSON.parse(result.smallImg).couponImg
                    }
                    headpicS.style.display = 'block'
                    detailpicS.style.display = 'block'
                    couponpicS.style.display = 'block'

                    //商品编
                    document.getElementById('Number').innerHTML = result.uuid;

                    //开始时间
                    document.getElementById('datefrom').innerHTML = fmtDate(result.beginTime)

                    //结束时间
                    document.getElementById('dateto').innerHTML = fmtDate(result.endTime)

                    //使用地址，对象
                    let teachbox = document.getElementById("teacherbox");
                    let parentsbox = document.getElementById("parentsbox");
                    let all = document.getElementById('all');
                    if (result.listArea.length > 0) {
                        if (result.listArea[0].putRange == 1) {
                            teachbox.checked = true;
                        } else if (result.listArea[0].putRange == 2) {
                            parentsbox.checked = true;
                        } else if (result.listArea[0].putRange == 0) {
                            parentsbox.checked = true;
                            teachbox.checked = true;
                        }
                        if (result.listArea[0].areaId == 'china') {
                            all.checked = 'checked';
                            all.disabled = 'disabled';
                        } else {
                            let uuid = result.listArea[0].areaId;
                            var editaddress = [];
                            $.ajax({
                                url: '/region/getPRegion.json ?uuid=' + uuid,
                                type: "post",
                                success: function(res) {
                                    let addr = res.data;
                                    let uuid = addr.uuid;
                                    editaddress.push(addr.childOrgName)
                                    editaddress.push(addr.orgName)
                                    $.ajax({
                                        url: '/region/getPRegion.json ?uuid=' + uuid,
                                        type: "post",
                                        success: function(res) {
                                            let addr = res.data;
                                            if (addr.puuid == 'china') {
                                                editaddress.push(addr.orgName)
                                                document.getElementById('editAddress').value = editaddress[2] + editaddress[1] + editaddress[0];
                                                document.getElementsByClassName('editAddress')[0].style.display = 'block'
                                            } else if (addr.uuid) {
                                                editaddress.push(addr.orgName)

                                            }
                                        }
                                    })
                                }
                            })


                        }

                    }

                    //是否展示禁用
                    parentsbox.disabled = true;
                    teachbox.disabled = true;
                    all.disabled = true;
                    rec.refs.cascader.props.disabled = true;
                    document.getElementById('isShow').disabled = true;
                    document.getElementsByClassName('stock')[0].disabled = true;
                    document.getElementsByClassName('goodsAddress')[0].style.display = 'none'
                    for (var v in refs) {
                        if (v == "name" || v == "consumeCredit" || v == "goodsType" || v == "contents" || v == "totalNum")
                            refs[v].value = result[v]
                    }


                }
            })
        }
    }

    //地区选择
    onChange = (value, selectedOptions) => {
        this.areaId = value
    }

    //地区数据加载渲染
    loadData = (selectedOptions) => {
        var rec = this;
        var pid = selectedOptions[0].value;
        let leaf = false;
        const targetOption = selectedOptions[selectedOptions.length - 1];
        targetOption.loading = true;
        if (selectedOptions.length == 2) {
            pid = selectedOptions[1].value;
            leaf = true;
        }
        $.ajax({
            url: '/region/getRegions',
            type: "post",
            dataType: "json",
            data: {
                uuid: pid
            },
            success: function(res) {
                if (res.code == 50006) {
                    var allData = [];
                    for (var i = 0; i < res.data.length; i++) {
                        allData.push({
                            value: res.data[i].uuid,
                            label: res.data[i].orgName,
                            isLeaf: leaf
                        })
                    }
                    // setTimeout(() => {
                    targetOption.loading = false;
                    targetOption.children = allData;
                    rec.setState({
                        options: [...rec.state.options],
                    });
                    // }, 1000);
                } else if (res.code == 50007) {
                    Toast.toast(res.data)
                }
            }
        })
        // load options lazily

    }

    handleClick(e) {
        this.setState({
            isOpen: true
        });
    }

    handleCancel() {
        this.setState({
            isOpen: false
        });
    }

    handleSelect(value) {
        document.getElementById(this.timeObj).innerHTML = dateFormat(new Date(value), '-', false);
        this.setState({
            value,
            isOpen: false
        });
    }

    //时间限制
    timeSplit(timeObj) {
        this.timeObj = timeObj;
        let value = this.state.value,
            min,
            max,
            timeValue = '';
        if (timeObj == 'datefrom') {
            min = new Date(GetDateStr(0))
            const dateto = document.getElementById('dateto').innerHTML;
            if (dateto != '') {
                max = new Date(dateto)
            } else {
                max = undefined
            }

        } else {
            const datefrom = document.getElementById('datefrom').innerHTML;
            min = new Date(datefrom)
            max = undefined
        }
        if (timeValue != '')
            value = new Date(timeValue)
        this.setState({
            isOpen: true,
            value,
            min,
            max
        });
    }

    onChange(value, dateString) {
        console.log('Selected Time: ', value);
        console.log('Formatted Selected Time: ', dateString);
    }

    onOk(value) {
        console.log('onOk: ', value);
    }

    //商家介绍字数限制
    textLength(e) {
        const length = e.target.value.length;
        if (length > 5) {
            Toast.toast('商家介绍字数限制在500以内！')
            return
        }
    }

    //图片上传，格式判断
    picUpload(e) {
        let rct = this;
        let picInput = e.target;
        let img = document.getElementById(picInput.id + 'S');

        var image = new Image();
        image.src = window.URL.createObjectURL(picInput.files[0]);
        let width, height;
        switch (picInput.id) {
            case 'headpic':
                width = 200;
                height = 200;
                break
            case 'detailpic':
                width = 750;
                height = 300;
                break
            case 'couponpic':
                width = 500;
                height = 130;
                break
            default:
        }
        image.onload = function() {
            const imgwidth = image.width;
            const imgheight = image.height;
            if (imgheight == height && imgwidth == width) {
                img.src = window.URL.createObjectURL(picInput.files[0]);
                img.style.display = 'block';
            } else {
                Toast.toast('请上传宽度为' + width + 'px, 高度为' + height + 'px 的图片！')
                return
            }
        };


    }

    //表单提交
    submitHandle(e) {
        e.preventDefault();
        let refs = this.refs;
        var rec = this;
        let btoken = localStorage.btoken;
        let companyId = localStorage.companyId;
        let data = {};
        for (let i in refs) {
            data[i] = refs[i].value;
        }

        //获取表单部分值
        for (let m in data) {
            if (data[m] == '') {
                Toast.toast(this.refs[m].nextSibling.innerHTML)
                return;
            }
        }

        //判断是否选择券有效期
        const start = document.getElementById("datefrom").innerHTML;
        let beginTime = new Date(start).setHours(0, 0, 0, 0)
        if (start == '开始时间') {
            Toast.toast('请选择开始时间！')
            return;
        }

        const end = document.getElementById("dateto").innerHTML;
        // debugger
        let endTime = new Date(end).setHours(23, 59, 59, 0);
        let stopTime = new Date().setHours(23, 59, 59, 0)
        if (endTime < stopTime) {
            Toast.toast('券的有效期已经过期！')
            return
        }
        if (end == '结束时间') {
            Toast.toast('请选择结束时间！')
            return;
        }

        //上传商品的三张图片，并获取返回值
        let allPic = ['headpic', 'detailpic', 'couponpic']
        let pic, picS, tip;
        data.smallImg = [];

        //goodId 为修改标识
        const goodId = this.goodId;
        for (let p in allPic) {
            //判断是否上传商品图片
            let item = allPic[p];
            pic = document.getElementById(item);
            picS = document.getElementById(item + 'S');
            if (pic.files.length == 0) {
                if (!goodId) {
                    switch (item) {
                        case 'headpic':
                            Toast.toast('请上传商品头图！')
                            return;
                        case 'detailpic':
                            tip = '图片详情图'
                            Toast.toast('请上传商品详情图！')
                            return;
                        default:

                    }
                }
            }
            if (pic.files.length > 0) {
                ApiUploadImg(pic.files[0], btoken, function(res, msg) {
                    data.smallImg.push(sxtUploadImgUse + '/images/' + res.status)
                })
            } else {
                data.smallImg.push(picS.src)
            }

        }

        let res = {
            "goodsArch": {
                "name": data.name,
                "contents": data.contents,
                "consumeCredit": data.consumeCredit, //需要消耗积分
                "totalNum": data.totalNum, //库存数量
                "beginTime": beginTime, //有效期开始时间
                "endTime": endTime, //有效期结束时间
                "usetimes": 1, //使用次数
                "goodsType": data.goodsType, //商品类型，1免费券 2特价券 3抵用券 4折扣券
                "price": 0, //市场价格
                "companyId": companyId
            }
        }
        // console.log(res.goodsArch.beginTime);
        // console.log(res.goodsArch.endTime);
        // return;

        const allData = this.goodDatas;
        if (goodId) {
            const change = ['name', 'goodsType', 'consumeCredit', 'contents'];
            var changeData = {
                    id: goodId
                },
                imgsData = [];
            for (let m = 0; m < change.length; m++) {
                if (allData[change[m]] != data[change[m]]) {
                    changeData[change[m]] = data[change[m]]
                }
            }
            let imgs = allData.smallImg;

            for (let n = 0; n < 3; n++) {
                if (imgs[n] != data.smallImg[n]) {
                    data.smallImg[n] = data.smallImg[n]
                }
            }
            let changeImgs = {
                "goodsHeaderImg": data.smallImg[0],
                "goodsDetailsImg": data.smallImg[1],
                "couponImg": data.smallImg[2]
            }
            changeData.smallImg = JSON.stringify(changeImgs)

            if (beginTime != allData.beginTime) {
                changeData.beginTime = beginTime
            }

            if (endTime != allData.endTime) {
                changeData.endTime = endTime
            }

            changeData.companyId = localStorage.companyId;
            if (!/^[\s+`~!@#$%^&*()\-=_+[\]{};'\\:"|,.<>/?·！￥…（）—【】；‘’、“”：，。《》、a-zA-Z0-9\u4E00-\u9FA5]+$/ig.test(changeData)) {
                Tips('提交内容有特殊字符')
                return
            }

            if (haveEmoji(JSON.stringify(changeData))) {
                Toast.toast('提交内容有特殊字符')
                return
            }

            //修改商品
            $.ajax({
                url: '/jf/business/goodsArchives/update?token=' + btoken,
                type: "post",
                dataType: "json",
                data: JSON.stringify(changeData),
                headers: {
                    'Content-Type': 'application/json'
                },
                success: function(res) {
                    if (res.code == 50006) {
                        Toast.toast(res.data)
                        rec.context.router.push('/goodsManage');
                    } else if (res.code == 50007) {
                        Toast.toast(res.data)
                    }
                }
            })

        } else {
            //添加商品

            //投放区域传值
            let add = document.getElementById('all').checked;
            res.listPutArea = []
            if (data.isShow == "1") {
                //判断是否选择使用对象
                let obj = document.getElementsByName("target");
                let target = [],
                    putRange;
                for (let n = 0; n < obj.length; n++) {
                    if (obj[n].checked)
                        target.push(obj[n].value);
                }
                if (target.length < 1) {
                    Toast.toast('请选择使用对象！')
                    return;
                } else if (target.length == 1) {
                    putRange = target[0]
                } else {
                    putRange = 0
                }
                if (add == true) {
                    res.listPutArea.push({
                        "areaId": "china", //投放区域ID
                        "putRange": putRange //投放范围，范围 0所有1教师2家长，默认为0
                    })
                } else {
                    //判断商品地址选择情况
                    if (this.areaId.length < 1) {
                        Toast.toast('请选择商品地址！')
                        return;
                    } else if (this.areaId.length < 3) {
                        Toast.toast('商品地址应该选择到区！')
                        return;
                    }

                    res.listPutArea.push({
                        "areaId": this.areaId[2], //投放区域ID
                        "putRange": putRange //投放范围，范围 0所有1教师2家长，默认为0
                    })
                }
            }
            let couponImgS = document.getElementById('couponpic').files.length;
            let allimgs = {
                "goodsHeaderImg": data.smallImg[0],
                "goodsDetailsImg": data.smallImg[1],
                "couponImg": couponImgS > 0 ? data.smallImg[2] : ''
            }

            res.goodsArch.smallImg = JSON.stringify(allimgs)
            if (!/^[\s+`~!@#$%^&*()\-=_+[\]{};'\\:"|,.<>/?·！￥…（）—【】；‘’、“”：，。《》、a-zA-Z0-9\u4E00-\u9FA5]+$/ig.test(res)) {
                Toast.toast('提交内容有特殊字符')
                return
            }

            if (haveEmoji(JSON.stringify(res))) {
                Toast.toast('提交内容有特殊字符')
                return
            }
            //添加商品
            $.ajax({
                url: '/jf/business/goodsArchives/submit?token=' + btoken,
                type: "post",
                dataType: "json",
                data: JSON.stringify(res),
                headers: {
                    'Content-Type': 'application/json'
                },
                success: function(res) {
                    if (res.code == 50006) {
                        Toast.toast(res.data)
                        rec.context.router.push('/goodsManage');
                    } else if (res.code == 50007) {
                        Toast.toast(res.data)
                    }
                }
            })
        }


    }

    //商品是否展示  地址和对象相应变化
    showChange(e) {
        const val = e.target.value;
        if (val == '0') {
            document.getElementsByClassName('goodsAddress')[0].style.display = 'none';
            document.getElementsByClassName('checkgroup')[0].style.display = 'none';

        } else {
            document.getElementsByClassName('goodsAddress')[0].style.display = 'block'
            document.getElementsByClassName('checkgroup')[0].style.display = 'block';
        }
    }

    //商品地址是否为全国，输入框的显示与隐藏
    choseChina(e) {
        const val = e.target;
        let address = document.getElementsByClassName('choseAddress')[0];
        let addressBox = document.getElementsByClassName('addressbox')[0]
        if (val.checked) {
            address.style.display = 'none';
            addressBox.style.paddingTop = '20px'
        } else {
            address.style.display = 'block';
            addressBox.style.paddingTop = 0
        }
    }

    render() {
        const {
            flag,
            contentNumber,
            isOpen,
            value,
            min,
            max
        } = this.state;
        return (
            <div>
                <R_header_fixed left="1" title={this.title}/>
                <div className="addGoods">
                    <form onSubmit={this.submitHandle.bind(this)}>
                        <div className="group">
                            <label >商品名称：</label>
                            <div className="inputbox">
                                <input type="text" ref="name" className="form-control"/>
                                <span className="errorSpan">请填写商品名称</span>
                            </div>
                        </div>
                        <div className="group" style={{margin: "20px 0"}}>
                            <label>商品编号：</label><span id="Number">系统自动生成 不需要填写</span>
                        </div>
                        <div className="group">
                            <label >商品类型：</label>
                            <div className="form-control chose">
                                <select ref="goodsType">
                                    <option value={1}>免费券</option>
                                    <option value={2}>特价券</option>
                                    <option value={3}>抵用券</option>
                                    <option value={4}>折扣券</option>
                                </select>
                                <img src={Chose}/>
                            </div>

                        </div>
                        <div className="group checkgroup">
                            <label >使用对象：</label>
                            <div className="targetbox">
                                <div className="check">
                                    <input type="checkbox" name="target" value='2' className="checkInput"
                                           id="parentsbox"/>
                                    <label for="myCheck"></label>
                                    <span>家长</span>
                                </div>
                                <div className="check">
                                    <input type="checkbox" name="target" value="1" className="checkInput"
                                           id="teacherbox"/>
                                    <label for="myCheck"></label>
                                    <span>老师</span>
                                </div>
                            </div>

                        </div>

                        <div className="group editAddress">
                            <label>商品地址：</label>
                            <div className="inputbox ">
                                <div className="form-control chose">
                                    <input id="editAddress" disabled='disabled'/>
                                    <img src={Chose}/>
                                </div>
                            </div>
                        </div>
                        <div className="group goodsAddress">
                            <label>商品地址：</label>
                            <div className="inputbox ">
                                <div className="form-control choseAddress chose">
                                    <Cascader
                                        ref="cascader"
                                        options={this.state.options}
                                        loadData={this.loadData.bind(this)}
                                        onChange={this.onChange.bind(this)}
                                        changeOnSelect
                                        placeholder="下拉选择"
                                    />
                                    <img src={Chose}/>
                                </div>
                                <span className="errorSpan">请填写商品地址！</span>
                                <div className="addressbox">
                                    <input type="checkbox" name="address" value="all" className="checkInput" id="all"
                                           onChange={this.choseChina.bind(this)}/>
                                    <label for="myCheck"></label>
                                    <span>全国</span>
                                </div>
                            </div>
                        </div>
                        <div className="group">
                            <label >商品价值：</label>
                            <input className="form-control" type="number" name="points" min="0"
                                   ref="consumeCredit"/>
                            <span className="errorSpan">请填写商品价值！</span>
                        </div>
                        <div className="group">
                            <label >是否展示：</label>
                            <div className="form-control chose">
                                <select id="isShow" ref="isShow" onChange={this.showChange.bind(this)}>
                                    <option value="1">是</option>
                                    <option value="0">否</option>
                                </select>
                                <img src={Chose}/>
                            </div>
                            <span className="tip">（选择是则代表商品可在积分商城中进行展示）</span>
                        </div>
                        <div className="group effectdate">
                            <label >券有效期：</label>
                            <div>
                                <div id="datefrom" onClick={this.timeSplit.bind(this, 'datefrom')}>开始时间</div>
                                <div className="separation">~</div>
                                <div id="dateto" onClick={this.timeSplit.bind(this, 'dateto')}>结束时间</div>
                            </div>

                        </div>
                        <div className="group">
                            <label >商品库存：</label>
                            <input className="form-control stock" type="number" name="points" min="0" ref="totalNum"/>
                            <span className="errorSpan">请填写商品库存！</span>
                        </div>
                        <div className="group">
                            <label >图片头图：</label>
                            <div className="upload">
                                <input type="button" className="addBtn" value='点击上传'/>
                                <input type="file" className="form-control fileinput" name="pic" id="headpic" wid="505"
                                       onChange={this.picUpload.bind(this)}/>
                                <img src="" id="headpicS"/>
                                <span className="tip">（用于积分商城首页的图片,尺寸为：宽200px*高200px）</span>
                            </div>
                        </div>

                        <div className="group">
                            <label >图片详情图：</label>
                            <div className="upload">
                                <input type="button" className="addBtn" value='点击上传'/>
                                <input type="file" className="form-control fileinput" name="pic" id="detailpic"
                                       onChange={this.picUpload.bind(this)}/>
                                <img src="" id="detailpicS"/>
                            </div>
                            <span className="tip">（商品详情页图片,尺寸为：宽750px*高300px）</span>
                        </div>

                        <div className="group">
                            <label >优惠券图片：</label>
                            <div className="upload">
                                <input type="button" className="addBtn" value='点击上传'/>
                                <input type="file" className="form-control fileinput" name="pic" id="couponpic"
                                       onChange={this.picUpload.bind(this)}/>
                                <span className="tip">（资讯文章内领券图片，尺寸为：宽500px*高130px）</span>
                                <img  id="couponpicS" alt="优惠券图片"/>
                            </div>
                        </div>

                        {/*<div className="group">
                            <label >商品介绍：</label>
                            <textarea type="text" className="form-control" placeholder="500字以内" maxLength='500'
                                      ref="contents"/>
                            <span className="errorSpan">请填写商品介绍！</span>
                        </div>*/}
                        <div className="form-group">
                            <button type="submit" className="btn Btn save">保存</button>
                        </div>
                    </form>
                    <DatePicker theme={browser().ios == true
                        ? 'ios'
                        : 'android'} showFormat="YYYY-MM-DD" value={value} min={min} max={max} isOpen={isOpen}
                                onSelect={this.handleSelect.bind(this)} onCancel={this.handleCancel.bind(this)}/>
                </div>
            </div>
        )
    }
}
